import { Controller } from 'egg';

export default class AddressController extends Controller {

  /**
   * 收货地址列表
   */
  async list() {
    const { openid: user_id } = this.ctx.state.user
    const shop_id = this.ctx._shop.id;
    const list = await this.ctx.model.Address.findAll({ where: { user_id, shop_id } });
    this.ctx.success({
      data: list,
    });
  }

  /**
   * 添加收货地址
   */
  async create() {
    const { body } = this.ctx.validateReq('address.create');
    const { openid: user_id } = this.ctx.state.user
    const shop_id = this.ctx._shop.id
    const { is_default } = body
    if (is_default === 1) {
      await this.ctx.model.Address.update({ is_default: 0 }, { where: { user_id, shop_id, is_default: 1 } });
    }
    const result = await this.ctx.service.wx.address.create({ ...body, user_id });

    this.ctx.success({
      data: {
        id: result.id,
      },
    });
  }

  async update() {
    const { body } = this.ctx.validateReq('address.update');
    const { openid: user_id } = this.ctx.state.user
    const shop_id = this.ctx._shop.id
    const { is_default } = body
    if (is_default === 1) {
      await this.ctx.model.Address.update({ is_default: 0 }, { where: { user_id, shop_id, is_default: 1 } });
    }
    const result = await this.ctx.service.wx.address.update(body.id, body);

    this.ctx.success({
      data: {
        id: result.id,
      },
    });
  }



  async detail() {
    const { params: { id } } = this.ctx.validateReq('address.detail');

    const data = await this.ctx.service.wx.address.detail(id);

    if (data) {
      this.ctx.success({
        data,
        status: 201,
      });
    }
  }


  async destroy() {
    const { params: { id } } = this.ctx.validateReq('address.destroy');

    const result = await this.ctx.service.wx.address.destroy(id);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }

}
